from sqlalchemy import Column, Integer, String, Float, DateTime, func
from models.base import Base
from models.base import session
import threading

# House.type
HOUSE_TYPE_NEW = 1  # 新房
HOUSE_TYPE_SECONDARY = 2  # 二手房
HOUSE_TYPE_RENT_DEFAULT = 3  # 普通租房
HOUSE_TYPE_RENT_APARTMENT = 4  # 公寓租房

# 同步锁，多线程时有用
_lock = threading.Lock()


class House(Base):
    __tablename__ = 'house'

    house_id = Column(Integer, primary_key=True, comment="id")
    type = Column(Integer, nullable=False, comment="信息类型：1=新房，2=二手房")
    community_code = Column(String(32), nullable=True, comment="小区编号")
    house_code = Column(String(32), nullable=False, comment="房屋编号")
    name = Column(String(32), nullable=False, comment="小区名称")
    city = Column(String(10), nullable=False, comment="城市")
    district = Column(String(32), nullable=False, comment="行政区")
    circle = Column(String(32), nullable=False, comment="商圈")
    price = Column(Float, nullable=False, comment="价格")
    area = Column(Float, nullable=False, comment="面积")
    bedroom = Column(Integer, nullable=False, comment="卧室")
    sitting_room = Column(Integer, nullable=True, default=0, comment="厅")
    create_time = Column(DateTime, nullable=True, server_default=func.now(), comment="创建时间")
    update_time = Column(DateTime, nullable=True, server_default=func.now(), onupdate=func.now(), comment="更新时间")

    def __repr__(self):
        return "<HouseInfo(house_id=%s, name=%s, type=%s, price=%s)>" % (
            self.house_id, self.name, self.type, self.price)

    def save(self):
        try:
            _lock.acquire()
            query = session.query(House).filter_by(house_code=self.house_code)
            house = query.first()
            if not house:
                session.add(self)
                session.commit()
            else:
                d = self.to_dict()
                del d["house_id"]
                del d["house_code"]
                del d["create_time"]
                del d["update_time"]
                query.update(d)
                session.commit()
        finally:
            _lock.release()
